<template>
    <div>
        <h1>审批</h1>
        <div class="operation-bar">
            <el-button type="primary" @click="handleAdd">添加申请</el-button>
        </div>
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="nurseName" label="申请人" width="180" />
            <el-table-column prop="replaceName" label="替班人" width="180" />
            <el-table-column prop="applicantType" label="申请类型" width="180"/>
            <el-table-column prop="reason" label="申请原因" width="180"/>
            <el-table-column prop="startTime" label="替班开始日期" width="180" />
            <el-table-column prop="endTime" label="替班结束日期" width="180"/>
            <el-table-column prop="auditComment" label="审批人意见" width="180"/>
            <el-table-column prop="auditState" label="审批状态" width="180">
                <template v-slot="scope">
                    <span>{{ scope.row.auditState === '2' ? '审批不通过' : scope.row.auditState === '1' ? '审批通过' : '待审批' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="auditorCode" label="审批人" width="180"/>
            <el-table-column prop="address" label="操作" width="180">
                <template #default="scope">
                    <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button type="primary" @click="Opperval(scope.row)">审批</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加申请对话框 -->
        <el-dialog v-model="dialogVisible" title="添加替班申请" width="50%">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="申请人" prop="nurseCode">
                    <el-select v-model="form.nurseCode" placeholder="请选择申请人" clearable>
                        <el-option v-for="item in nurseOptions" :key="item.nurseCode" :label="item.name" :value="item.nurseCode" />
                    </el-select>
                </el-form-item>

                <el-form-item label="替班人" prop="replaceCode">
                    <el-select v-model="form.replaceCode" placeholder="请选择替班人" clearable>
                        <el-option v-for="item in replace" :key="item.replaceCode" :label="item.replaceName" :value="item.replaceCode" />
                    </el-select>
                </el-form-item>

                <el-form-item label="申请类型" prop="applicantType">
                    <el-select v-model="form.applicantType" placeholder="请选择申请类型" clearable>
                        <el-option label="休假" value="休假"/>
                        <el-option label="调休" value="调休"/>
                        <el-option label="事假" value="事假"/>
                        <el-option label="病假" value="病假"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="申请原因" prop="reason">
                    <el-input v-model="form.reason" type="textarea" :rows="4" placeholder="请输入申请原因" maxlength="200" show-word-limit />
                </el-form-item>

                <el-form-item label="替班日期" required>
                    <div class="date-picker-group">
                        <el-form-item prop="startTime">
                            <el-date-picker v-model="form.startTime" type="date" placeholder="开始日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :disabled-date="disablePastDates" @change="validateDates" />
                        </el-form-item>
                        <span class="date-separator">至</span>
                        <el-form-item prop="endTime">
                            <el-date-picker v-model="form.endTime" type="date" placeholder="结束日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :disabled-date="disablePastDates" @change="validateDates" />
                        </el-form-item>
                    </div>
                </el-form-item>

                <el-form-item label="审核人" prop="auditorCode">
                    <el-input v-model="form.auditorCode" placeholder="请输入审核人" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>




    </div>

    <div>
  <!-- 修改申请对话框 -->
        <el-dialog v-model="dialogVisibleupdate" title="修改替班申请" width="50%">
            <el-form ref="formRefUpdate" :model="formupdate" :rules="rules" label-width="120px">
                <el-form-item label="申请人" prop="nurseCode">
                    <el-select v-model="formupdate.nurseCode" placeholder="请选择申请人" clearable>
                        <el-option v-for="item in nurseOptions" :key="item.nurseCode" :label="item.name" :value="item.nurseCode" />
                    </el-select>
                </el-form-item>

                <el-form-item label="替班人" prop="replaceCode">
                    <el-select v-model="formupdate.replaceCode" placeholder="请选择替班人" clearable>
                        <el-option v-for="item in replace" :key="item.replaceCode" :label="item.replaceName" :value="item.replaceCode" />
                    </el-select>
                </el-form-item>

                <el-form-item label="申请类型" prop="applicantType">
                    <el-select v-model="formupdate.applicantType" placeholder="请选择申请类型" clearable>
                        <el-option label="休假" value="休假"/>
                        <el-option label="调休" value="调休"/>
                        <el-option label="事假" value="事假"/>
                        <el-option label="病假" value="病假"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="申请原因" prop="reason">
                    <el-input v-model="formupdate.reason" type="textarea" :rows="4" placeholder="请输入申请原因" maxlength="200" show-word-limit />
                </el-form-item>

                <el-form-item label="替班日期" required>
                    <div class="date-picker-group">
                        <el-form-item prop="startTime">
                            <el-date-picker v-model="formupdate.startTime" type="date" placeholder="开始日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :disabled-date="disablePastDates" @change="validateDates" />
                        </el-form-item>
                        <span class="date-separator">至</span>
                        <el-form-item prop="endTime">
                            <el-date-picker v-model="formupdate.endTime" type="date" placeholder="结束日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :disabled-date="disablePastDates" @change="validateDates" />
                        </el-form-item>
                    </div>
                </el-form-item>

                <el-form-item label="审核人" prop="auditorCode">
                    <el-input v-model="formupdate.auditorCode" placeholder="请输入审核人" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisibleupdate = false">取消</el-button>
                    <el-button type="primary" @click="submitFormupdate(formRefUpdate)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

   <!-- 审批弹框 -->
   <el-dialog
    v-model="dialogVisibleOpperval"
    title="审批"
    width="50%"
    center
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    class="approval-dialog"
    top="20vh"
  >
  <el-form :model="form" label-width="120px">
    <el-form-item label="审批状态">
      <el-radio-group v-model="form.auditState">
        <el-radio value="1">同意</el-radio>
        <el-radio value="2">拒绝</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="审批意见" :rules="[{ required: form.auditState === 2, message: '拒绝时必须填写审批意见', trigger: 'blur' }]">
      <el-input v-model="form.auditComment" type="textarea" :rows="4" placeholder="请输入审批意见" />
    </el-form-item>
</el-form>
<template #footer>
  <span class="dialog-footer">
    <el-button @click="dialogVisibleOpperval = false">取消</el-button>
    <el-button type="primary" @click="submitApproval">确定</el-button>
  </span>
</template>
  </el-dialog>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import http from '@/api/http';
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const formRefUpdate = ref<FormInstance>()
const dialogVisible = ref(false)
const dialogVisibleupdate = ref(false)// 修改申请对话框
const tableData = ref([])
const nurseOptions:any = ref([])
const replace:any = ref([])

// 表单数据
const form = reactive({
    id: '',
    nurseCode: '',
    replaceCode: '',
    applicantType: '',
    reason: '',
    startTime: '',
    endTime: '',
    auditState: 1, // 默认为同意，审核通过
    auditorCode: '',
    auditComment:'',
    isDel: '0' // 默认未删除
})


const handleEdit = (row: any) => {
    dialogVisibleupdate.value = true
    formupdate.id = row.id
    formupdate.nurseCode = row.nurseCode
    formupdate.replaceCode = row.replaceCode
    formupdate.applicantType = row.applicantType
    formupdate.reason = row.reason
    formupdate.startTime = row.startTime
    formupdate.endTime = row.endTime
    formupdate.auditorCode= row.auditorCode
}

// 修改表单数据
const formupdate = reactive({
    id: '',
    nurseCode: '',
    replaceCode: '',
    applicantType: '',
    reason: '',
    startTime: '',
    endTime: '',
    auditState: '0', // 默认待审核
    auditorCode: '',
    auditComment:'',
    isDel: '0' // 默认未删除
})




// 表单验证规则
const rules = reactive<FormRules>({
    nurseCode: [
        { required: true, message: '请选择申请人', trigger: 'change' }
    ],
    replaceCode: [
        { required: true, message: '请选择替班人', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (value === form.nurseCode) {
                    callback(new Error('替班人不能是申请人本人'))
                } else {
                    callback()
                }
            },
            trigger: 'change'
        }
    ],
    applicantType: [
        { required: true, message: '请选择申请类型', trigger: 'change' }
    ],
    reason: [
        { required: true, message: '请输入申请原因', trigger: 'blur' }
    ],
    startTime: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
    ],
    endTime: [
        { required: true, message: '请选择结束日期', trigger: 'change' }
    ],
    auditorCode: [
        { required: true, message: '请输入审核人', trigger: 'blur' }
    ]
})

// 禁用过去的日期
const disablePastDates = (date: Date) => {
    return date.getTime() < Date.now() - 8.64e7
}

// 验证日期
const validateDates = () => {
    if (form.startTime && form.endTime) {
        const start = new Date(form.startTime).getTime()
        const end = new Date(form.endTime).getTime()
        if (end < start) {
            form.endTime = ''
            ElMessage.warning('结束日期不能早于开始日期')
        }
    }
}

// 添加申请
const handleAdd = () => {
    dialogVisible.value = true
    // 重置表单
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post('/api/ReplaceWorkController/AddReplaceWork', form).then(res => {
                   console.log('提交数据', form)
                ElMessage.success('申请成功')
                dialogVisible.value = false
                getTableData() // 刷新表格数据
            }).catch(err => {
                ElMessage.error('申请失败')
            })
        } else {
            ElMessage.error('请检查输入内容')
        }
    })
}


// 修改提交表单
const submitFormupdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post('/api/ReplaceWorkController/UpdateReplaceWork', formupdate).then(res => {
                ElMessage.success('修改成功')
                console.log('提交修改数据', formupdate.id)
                dialogVisibleupdate.value = false
                getTableData() // 刷新表格数据
            }).catch(err => {
                ElMessage.error('修改失败')
            })
        } else {
            ElMessage.error('请检查输入内容')
        }
    })
}

// 获取护士列表
const getNurseList = async () => {
    http.get('/api/ReplaceWorkController/ReplaceWorkShow').then(res => {
        nurseOptions.value = res
    })
}

// 获取替班人列表
const replaceCodeOptions = async () => {
    http.get('/api/ReplaceWorkController/ReplaceTableShow').then(res => {
        replace.value = res
    })
}

const getTableData = async () => {
    http.get('/api/ReplaceWorkController/ReplaceWorkShows').then(res => {
        tableData.value = res
    }).catch(err => {
        console.log(err)
    })
}

//审批
const dialogVisibleOpperval=ref(false)
const currentRow = ref<any>(null)
const Opperval=(row:any)=>{
    dialogVisibleOpperval.value=true
    currentRow.value = row
    form.auditState = 1 // 默认选择"同意"
    form.auditComment = "" // 清空审批意见
}

// 提交审批
const submitApproval = () => {
    // 审批状态值：1=同意/已通过，2=拒绝/未通过
    const auditStateVal = form.auditState === 1 ? 1 : 0
    
    if (form.auditState === 2 && !form.auditComment) {
        ElMessage.warning('拒绝时必须填写审批意见')
        return
    }
    
    handleApproval(currentRow.value.id, auditStateVal, form.auditComment)
    dialogVisibleOpperval.value = false
}

const handleApproval = (id:any, auditState:any, auditComment:string='') => {
    // 确保id不为null
    if (!id) {
        ElMessage.error('审批数据ID不存在')
        return
    }
    
    // 构建符合后端API期望的数据结构
    const params = {
        id: id,
        auditState: auditState,
        auditComment: auditComment || ''  // 确保审批意见即使为空也是空字符串
    }
    
    console.log('发送审批数据:', params) // 调试日志
    params.auditState=form.auditState
    params.auditComment=form.auditComment
    http.post('/api/ReplaceWorkController/UpdateAuditState?id='+params.id+'&auditState='+params.auditState+'&auditComment='+params.auditComment).then(res => {
        if(auditState === 1) {
            ElMessage.success('审批通过成功')
        } else {
            ElMessage.warning('审批未通过')
        }
        getTableData() // 刷新表格数据以显示最新状态
    }).catch(err => {
        console.log('审批失败', err)
        ElMessage.error('审批操作失败: ' + (err.message || '未知错误'))
    })
}

onMounted(() => {
    getTableData()
    getNurseList()
    replaceCodeOptions()
})

</script>

<style scoped>
.operation-bar {
    margin-bottom: 20px;
    padding: 10px 0;
}

.date-picker-group {
    display: flex;
    align-items: center;
    gap: 10px;
}

.date-separator {
    color: #606266;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-form-item__content) {
    flex-wrap: nowrap;
}

/* 审批弹框样式 */
:deep(.approval-dialog) {
  display: flex;
  align-items: center;
  justify-content: center;
  
  .el-dialog {
    margin: 0 auto !important;
    max-width: 90%;
  }
  
  .el-dialog__body {
    padding: 30px 40px;
    min-height: 120px;
  }
  
  .el-dialog__header {
    padding: 20px;
    text-align: center;
    font-weight: bold;
    font-size: 20px;
    border-bottom: 1px solid #EBEEF5;
  }
  
  .el-dialog__footer {
    padding: 20px;
    border-top: 1px solid #EBEEF5;
    display: flex;
    justify-content: center;
  }
  
  .el-form-item {
    margin-bottom: 25px;
  }
}
</style>